package com.echo.util.impl;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by houyong on 16-9-12.
 */
public class ExcelExportUtil {
	private static String EXCEL_HSSF_CONTENT_TYPE = "application/vnd.ms-excel";

	private static String EXCEL_HSSF_HEADER = "Content-disposition";

	private static String EXCEL_HSSF_ATTACHMENT = "attachment;filename=";

	private static String EXCEL_HSSF_PREFIX = ".xls";

	@SuppressWarnings("rawtypes")
	public void exportExcel(HttpServletResponse response, String filename, List<String> headList, List<List> datalist)
			throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();// 第一步,创建一个webbook,对应一个excel文件
		HSSFSheet sheet = workbook.createSheet();// 第二步,在webbook中添加

		HSSFCellStyle headStyle = workbook.createCellStyle();
		headStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 设置头的样式为居中

		HSSFCellStyle dataStyle = workbook.createCellStyle();
		dataStyle = workbook.createCellStyle();
		dataStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 设置数据的样式为居中

		int headrowstart = 0;
		HSSFRow headrow = sheet.createRow(headrowstart);// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		for (int i = 0; i < headList.size(); i++) {// 使用循环的方法,给头赋上值
			HSSFCell cell = headrow.createCell(i);
			cell.setCellStyle(headStyle);// 设置样式
			cell.setCellValue(headList.get(i));// 设置数据
		}
		int datarowstart = 1; // 数据从第一行开始进行插入
		for (List rowdata : datalist) { // 通过循环datalist进行写入数据
			HSSFRow row = sheet.createRow(datarowstart);// 第四步，创建单元格，并设置值
			for (int i = 0; i < rowdata.size(); i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(dataStyle);
				cell.setCellValue(String.valueOf(rowdata.get(i)));
			}
			datarowstart++;// 行数+1
		}
		response.setContentType(EXCEL_HSSF_CONTENT_TYPE);// 定义输出类型
		response.setHeader(EXCEL_HSSF_HEADER, EXCEL_HSSF_ATTACHMENT + filename + EXCEL_HSSF_PREFIX);//// 设定输出文件头
		OutputStream ouputStream = null;
		try {
			ouputStream = response.getOutputStream();// 通过输出流进行输出文件
			workbook.write(ouputStream);
			ouputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (ouputStream != null) {
				ouputStream.close();
			}
		}
	}
}
